<template>
  <view class="assign-task-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="指派任务" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 工单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">工单状态：</text>
              <up-tabs :list="statusList" :scrollable="false" @change="handleStatusChange" :current="currentStatus"></up-tabs>
            </view>
            
            <!-- 时间筛选 -->
            <view class="filter-item">
              <text class="filter-label">时间筛选：</text>
              <up-tabs :list="timeRangeList" :scrollable="true" @change="handleTimeRangeChange" :current="currentTimeRange"></up-tabs>
            </view>
            
            <!-- 自定义时间选择 -->
            <view v-if="currentTimeRange === 5" class="custom-time-section">
              <view class="time-picker-row">
                <view class="time-picker">
                  <text class="title">自定义时间</text>
                  <uni-datetime-picker type="daterange" :border="false" v-model="customTimeRange.dateRange" @change="handleDateRangeChange"></uni-datetime-picker>
                </view>
              </view>
            </view>
            
            <!-- 模糊搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="true" 
                placeholder="请输入泊位号、停车场或设备编号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="assign-task-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              工单编号：<text class="number">{{ item.orderNo }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">负责人：</text>
                <text class="value">{{ item.assigneeName || '未指派' }}</text>
              </view>
              <view class="item">
                <text class="label">工单类型：</text>
                <text class="value work-order-type" :class="getWorkOrderTypeClass(item.workOrderType)">{{ item.workOrderType }}</text>
              </view>
              <view class="item">
                <text class="label">异常类型：</text>
                <text class="value exception-type" :class="getExceptionTypeClass(item.exceptionType)">{{ item.exceptionType }}</text>
              </view>
              <view class="item">
                <text class="label">泊位号：</text>
                <text class="value">{{ item.berthNumber }}</text>
              </view>
              <view class="item">
                <text class="label">设备编号：</text>
                <text class="value">{{ item.deviceSN }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="info" text="查看详情" class="custom-style" 
                  @click="handleViewDetail(item)"></up-button>
                <up-button v-if="item.status === 'unassigned'" type="primary" text="指派任务" class="custom-style" 
                  @click="handleAssignTask(item)"></up-button>
                <up-button type="success" text="创建任务" class="custom-style" 
                  @click="handleCreateTask(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 指派任务弹窗 -->
    <up-popup v-model:show="showAssignModal" mode="center" :round="10">
      <view class="assign-modal">
        <view class="modal-header">
          <text class="modal-title">指派任务</text>
          <up-icon name="close" @click="closeAssignModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">选择巡检员：</text>
            <up-search v-model="assignForm.inspectorKeyword" placeholder="搜索巡检员" @search="searchInspector"></up-search>
            
            <!-- 在岗离岗状态筛选 -->
            <view class="status-filter">
              <up-radio-group v-model="assignForm.statusFilter" @change="handleStatusFilterChange">
                <up-radio name="all" label="全部"></up-radio>
                <up-radio name="online" label="在岗"></up-radio>
                <up-radio name="offline" label="离岗"></up-radio>
              </up-radio-group>
            </view>
            
            <view class="inspector-list">
              <view class="inspector-item" v-for="inspector in filteredInspectors" :key="inspector.id"
                @click="toggleInspectorSelection(inspector)" :class="{ active: isInspectorSelected(inspector.id) }">
                <view class="inspector-info">
                  <text class="inspector-name">{{ inspector.name }}</text>
                  <text class="inspector-phone">{{ inspector.phone }}</text>
                  <view class="inspector-status" :class="inspector.status">
                    <text>{{ inspector.status === 'online' ? '在岗' : '离岗' }}</text>
                  </view>
                </view>
                <view class="selection-indicator" v-if="isInspectorSelected(inspector.id)">
                  <up-icon name="checkmark" color="#007AFF"></up-icon>
                </view>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="assignForm.remark" placeholder="请输入备注信息" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeAssignModal">取消</up-button>
          <up-button type="primary" @click="confirmAssign">确认指派</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 查看详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="center" :round="10">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ currentDetail.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位编号：</text>
            <text class="detail-value">{{ currentDetail.berthNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号：</text>
            <text class="detail-value">{{ currentDetail.deviceSN }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">工单类型：</text>
            <text class="detail-value">{{ currentDetail.workOrderType }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常类型：</text>
            <text class="detail-value">{{ currentDetail.exceptionType }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">备注：</text>
            <text class="detail-value">{{ currentDetail.remark || '无' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">处理状态：</text>
            <text class="detail-value">{{ getStatusText(currentDetail.status) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">处理时间：</text>
            <text class="detail-value">{{ currentDetail.processTime || '未处理' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">提交时间：</text>
            <text class="detail-value">{{ currentDetail.createTime }}</text>
          </view>
          <view class="detail-item" v-if="currentDetail.images && currentDetail.images.length > 0">
            <text class="detail-label">图片：</text>
            <view class="detail-images">
              <image v-for="(img, index) in currentDetail.images" :key="index" :src="img" mode="aspectFit" class="detail-image"></image>
            </view>
          </view>
          <view class="detail-item">
            <text class="detail-label">巡检员：</text>
            <text class="detail-value">{{ currentDetail.assigneeName || '未指派' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" @click="closeDetailModal">关闭</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 创建任务弹窗 -->
    <up-popup v-model:show="showCreateModal" mode="center" :round="10">
      <view class="create-modal">
        <view class="modal-header">
          <text class="modal-title">创建任务</text>
          <up-icon name="close" @click="closeCreateModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">泊位编号：</text>
            <up-input v-model="createForm.berthNumber" placeholder="请输入泊位编号"></up-input>
          </view>
          <view class="form-item">
            <text class="form-label">设备编号：</text>
            <up-input v-model="createForm.deviceSN" placeholder="请输入设备编号"></up-input>
          </view>
          <view class="form-item">
            <text class="form-label">工单类型：</text>
            <up-picker :columns="workOrderTypeColumns" @confirm="handleWorkOrderTypeChange">
              <up-input v-model="createForm.workOrderType" placeholder="请选择工单类型" readonly></up-input>
            </up-picker>
          </view>
          <view class="form-item">
            <text class="form-label">异常类型：</text>
            <up-picker :columns="exceptionTypeColumns" @confirm="handleExceptionTypeChange">
              <up-input v-model="createForm.exceptionType" placeholder="请选择异常类型" readonly></up-input>
            </up-picker>
          </view>
          <view class="form-item">
            <text class="form-label">停车场：</text>
            <up-input v-model="createForm.parkingLot" placeholder="请输入停车场"></up-input>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="createForm.remark" placeholder="请输入备注信息" maxlength="200"></up-textarea>
          </view>
          <view class="form-item">
            <text class="form-label">图片：</text>
            <view class="image-upload">
              <view class="image-list">
                <view class="image-item" v-for="(img, index) in createForm.images" :key="index">
                  <image :src="img" mode="aspectFit" class="uploaded-image"></image>
                  <view class="delete-btn" @click="removeImage(index)">
                    <up-icon name="close" color="#fff" size="12"></up-icon>
                  </view>
                </view>
                <view class="upload-btn" @click="chooseImage" v-if="createForm.images.length < 9">
                  <up-icon name="plus" color="#999" size="24"></up-icon>
                  <text>添加图片</text>
                </view>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">选择巡检员：</text>
            <up-search v-model="createForm.inspectorKeyword" placeholder="搜索巡检员" @search="searchCreateInspector"></up-search>
            
            <!-- 在岗离岗状态筛选 -->
            <view class="status-filter">
              <up-radio-group v-model="createForm.statusFilter" @change="handleCreateStatusFilterChange">
                <up-radio name="all" label="全部"></up-radio>
                <up-radio name="online" label="在岗"></up-radio>
                <up-radio name="offline" label="离岗"></up-radio>
              </up-radio-group>
            </view>
            
            <view class="inspector-list">
              <view class="inspector-item" v-for="inspector in filteredCreateInspectors" :key="inspector.id"
                @click="toggleCreateInspectorSelection(inspector)" :class="{ active: isCreateInspectorSelected(inspector.id) }">
                <view class="inspector-info">
                  <text class="inspector-name">{{ inspector.name }}</text>
                  <text class="inspector-phone">{{ inspector.phone }}</text>
                  <view class="inspector-status" :class="inspector.status">
                    <text>{{ inspector.status === 'online' ? '在岗' : '离岗' }}</text>
                  </view>
                </view>
                <view class="selection-indicator" v-if="isCreateInspectorSelected(inspector.id)">
                  <up-icon name="checkmark" color="#007AFF"></up-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeCreateModal">取消</up-button>
          <up-button type="primary" @click="confirmCreate">确认创建</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';

// 工单状态选项
const statusList = [
  { name: '全部' },
  { name: '待指派' },
  { name: '待处理' },
  { name: '已处理' },
];
const currentStatus = ref(0);

// 时间筛选选项
const timeRangeList = [
  { name: '近7天' },
  { name: '近1个月' },
  { name: '近3个月' },
  { name: '近半年' },
  { name: '近1年' },
  { name: '自定义' },
];
const currentTimeRange = ref(0);

// 自定义时间范围
const customTimeRange = reactive({
  startTime: '',
  endTime: '',
  dateRange: []
});

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 指派任务相关
const showAssignModal = ref(false);
const assignForm = reactive({
  inspectorKeyword: '',
  selectedInspectors: [],
  statusFilter: 'all',
  remark: ''
});
const currentAssignItem = ref(null);

// 创建任务相关
const showCreateModal = ref(false);
const createForm = reactive({
  berthNumber: '',
  deviceSN: '',
  workOrderType: '',
  exceptionType: '',
  parkingLot: '',
  remark: '',
  images: [],
  inspectorKeyword: '',
  selectedInspectors: [],
  statusFilter: 'all'
});

// 工单类型选项
const workOrderTypeColumns = [[
  { text: '运维工单', value: '运维工单' },
  { text: '巡检工单', value: '巡检工单' },
  { text: '退款工单', value: '退款工单' },
  { text: '异常工单', value: '异常工单' },
  { text: '故障工单', value: '故障工单' },
  { text: '异常泊位', value: '异常泊位' },
]];

// 异常类型选项
const exceptionTypeColumns = [[
  { text: '设备离线', value: '设备离线' },
  { text: '低电量预警', value: '低电量预警' },
  { text: '秒图异常', value: '秒图异常' },
  { text: '设备时间异常', value: '设备时间异常' },
  { text: '设备损坏', value: '设备损坏' },
  { text: '网络异常', value: '网络异常' },
  { text: '其他异常', value: '其他异常' },
]];

// 巡检员列表
const inspectorList = ref([
  { id: 1, name: '张三', phone: '13800138001', status: 'online' },
  { id: 2, name: '李四', phone: '13800138002', status: 'online' },
  { id: 3, name: '王五', phone: '13800138003', status: 'offline' },
  { id: 4, name: '赵六', phone: '13800138004', status: 'online' },
  { id: 5, name: '钱七', phone: '13800138005', status: 'offline' },
  { id: 6, name: '孙八', phone: '13800138006', status: 'online' },
]);

// 过滤后的巡检员列表（指派任务用）
const filteredInspectors = computed(() => {
  let filtered = inspectorList.value;
  
  // 根据关键词筛选
  if (assignForm.inspectorKeyword) {
    filtered = filtered.filter(inspector => 
      inspector.name.includes(assignForm.inspectorKeyword) || 
      inspector.phone.includes(assignForm.inspectorKeyword)
    );
  }
  
  // 根据在岗状态筛选
  if (assignForm.statusFilter !== 'all') {
    filtered = filtered.filter(inspector => inspector.status === assignForm.statusFilter);
  }
  
  return filtered;
});

// 过滤后的巡检员列表（创建任务用）
const filteredCreateInspectors = computed(() => {
  let filtered = inspectorList.value;
  
  // 根据关键词筛选
  if (createForm.inspectorKeyword) {
    filtered = filtered.filter(inspector => 
      inspector.name.includes(createForm.inspectorKeyword) || 
      inspector.phone.includes(createForm.inspectorKeyword)
    );
  }
  
  // 根据在岗状态筛选
  if (createForm.statusFilter !== 'all') {
    filtered = filtered.filter(inspector => inspector.status === createForm.statusFilter);
  }
  
  return filtered;
});

// 查看详情相关
const showDetailModal = ref(false);
const currentDetail = ref({});

// 工单状态切换事件
const handleStatusChange = (e) => {
  currentStatus.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 时间筛选切换事件
const handleTimeRangeChange = (e) => {
  currentTimeRange.value = e.index;
  // 如果不是自定义时间范围，则清空自定义时间
  if (currentTimeRange.value !== 5) {
    customTimeRange.dateRange = [];
    customTimeRange.startTime = '';
    customTimeRange.endTime = '';
  }
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  if (Array.isArray(e) && e.length === 2) {
    customTimeRange.startTime = e[0];
    customTimeRange.endTime = e[1];
    if (paging.value) {
      paging.value.reload();
    }
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.keyword = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.navigateBack();
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'unassigned': 'status-unassigned',
    'pending': 'status-pending',
    'processing': 'status-processing',
    'completed': 'status-completed'
  };
  return statusMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'unassigned': '待指派',
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已处理'
  };
  return statusMap[status] || status;
};

// 获取工单类型样式类
const getWorkOrderTypeClass = (type) => {
  const typeMap = {
    '运维工单': 'type-maintenance',
    '巡检工单': 'type-inspection',
    '退款工单': 'type-refund',
    '异常工单': 'type-exception',
    '故障工单': 'type-fault',
    '异常泊位': 'type-abnormal-berth'
  };
  return typeMap[type] || '';
};

// 获取异常类型样式类
const getExceptionTypeClass = (type) => {
  const typeMap = {
    '设备离线': 'type-offline',
    '低电量预警': 'type-low-battery',
    '秒图异常': 'type-image-error',
    '设备时间异常': 'type-time-error',
    '设备损坏': 'type-damage',
    '网络异常': 'type-network-error',
    '其他异常': 'type-other'
  };
  return typeMap[type] || '';
};

// 指派任务
const handleAssignTask = (item) => {
  currentAssignItem.value = item;
  assignForm.selectedInspectors = [];
  assignForm.inspectorKeyword = '';
  assignForm.statusFilter = 'all';
  assignForm.remark = '';
  showAssignModal.value = true;
};

// 搜索巡检员
const searchInspector = () => {
  // 搜索逻辑已在computed中实现
};

// 处理在岗状态筛选变化
const handleStatusFilterChange = (value) => {
  assignForm.statusFilter = value;
};

// 切换巡检员选择状态
const toggleInspectorSelection = (inspector) => {
  const index = assignForm.selectedInspectors.findIndex(item => item.id === inspector.id);
  if (index > -1) {
    assignForm.selectedInspectors.splice(index, 1);
  } else {
    assignForm.selectedInspectors.push(inspector);
  }
};

// 检查巡检员是否被选中
const isInspectorSelected = (inspectorId) => {
  return assignForm.selectedInspectors.some(item => item.id === inspectorId);
};

// 确认指派
const confirmAssign = () => {
  if (assignForm.selectedInspectors.length === 0) {
    uni.showToast({
      title: '请选择巡检员',
      icon: 'none'
    });
    return;
  }
  
  // 这里应该调用API进行指派
  uni.showToast({
    title: '指派成功',
    icon: 'success'
  });
  
  closeAssignModal();
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭指派弹窗
const closeAssignModal = () => {
  showAssignModal.value = false;
};

// 查看详情
const handleViewDetail = (item) => {
  currentDetail.value = item;
  showDetailModal.value = true;
};

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false;
};

// 创建任务
const handleCreateTask = () => {
  createForm.berthNumber = '';
  createForm.deviceSN = '';
  createForm.workOrderType = '';
  createForm.exceptionType = '';
  createForm.parkingLot = '';
  createForm.remark = '';
  createForm.images = [];
  createForm.inspectorKeyword = '';
  createForm.selectedInspectors = [];
  createForm.statusFilter = 'all';
  showCreateModal.value = true;
};

// 处理工单类型选择
const handleWorkOrderTypeChange = (e) => {
  createForm.workOrderType = e.value[0];
};

// 处理异常类型选择
const handleExceptionTypeChange = (e) => {
  createForm.exceptionType = e.value[0];
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - createForm.images.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      createForm.images.push(...res.tempFilePaths);
    }
  });
};

// 删除图片
const removeImage = (index) => {
  createForm.images.splice(index, 1);
};

// 搜索巡检员（创建任务用）
const searchCreateInspector = () => {
  // 搜索逻辑已在computed中实现
};

// 处理在岗状态筛选变化（创建任务用）
const handleCreateStatusFilterChange = (value) => {
  createForm.statusFilter = value;
};

// 切换巡检员选择状态（创建任务用）
const toggleCreateInspectorSelection = (inspector) => {
  const index = createForm.selectedInspectors.findIndex(item => item.id === inspector.id);
  if (index > -1) {
    createForm.selectedInspectors.splice(index, 1);
  } else {
    createForm.selectedInspectors.push(inspector);
  }
};

// 检查巡检员是否被选中（创建任务用）
const isCreateInspectorSelected = (inspectorId) => {
  return createForm.selectedInspectors.some(item => item.id === inspectorId);
};

// 确认创建
const confirmCreate = () => {
  if (!createForm.berthNumber) {
    uni.showToast({
      title: '请输入泊位编号',
      icon: 'none'
    });
    return;
  }
  
  if (!createForm.deviceSN) {
    uni.showToast({
      title: '请输入设备编号',
      icon: 'none'
    });
    return;
  }
  
  if (!createForm.workOrderType) {
    uni.showToast({
      title: '请选择工单类型',
      icon: 'none'
    });
    return;
  }
  
  if (!createForm.exceptionType) {
    uni.showToast({
      title: '请选择异常类型',
      icon: 'none'
    });
    return;
  }
  
  if (!createForm.parkingLot) {
    uni.showToast({
      title: '请输入停车场',
      icon: 'none'
    });
    return;
  }
  
  if (createForm.selectedInspectors.length === 0) {
    uni.showToast({
      title: '请选择巡检员',
      icon: 'none'
    });
    return;
  }
  
  // 这里应该调用API进行创建
  uni.showToast({
    title: '创建成功',
    icon: 'success'
  });
  
  closeCreateModal();
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭创建弹窗
const closeCreateModal = () => {
  showCreateModal.value = false;
};

// 获取指派任务列表数据
const queryList = async (pageNo, pageSize) => {
  const params = {
    pageNum: pageNo,
    pageSize,
    status: currentStatus.value,
    timeRange: currentTimeRange.value,
    keyword: searchForm.keyword
  };

  // 如果是自定义时间，添加时间参数
  if (currentTimeRange.value === 5 && customTimeRange.dateRange && customTimeRange.dateRange.length === 2) {
    params.startTime = customTimeRange.dateRange[0];
    params.endTime = customTimeRange.dateRange[1];
  } else if (currentTimeRange.value === 0) {
    // 近7天
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 7);
    params.startTime = startDate.toISOString().split('T')[0];
    params.endTime = endDate.toISOString().split('T')[0];
  } else if (currentTimeRange.value === 1) {
    // 近1个月
    const endDate = new Date();
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth() - 1);
    params.startTime = startDate.toISOString().split('T')[0];
    params.endTime = endDate.toISOString().split('T')[0];
  } else if (currentTimeRange.value === 2) {
    // 近3个月
    const endDate = new Date();
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth() - 3);
    params.startTime = startDate.toISOString().split('T')[0];
    params.endTime = endDate.toISOString().split('T')[0];
  } else if (currentTimeRange.value === 3) {
    // 近半年
    const endDate = new Date();
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth() - 6);
    params.startTime = startDate.toISOString().split('T')[0];
    params.endTime = endDate.toISOString().split('T')[0];
  } else if (currentTimeRange.value === 4) {
    // 近1年
    const endDate = new Date();
    const startDate = new Date();
    startDate.setFullYear(startDate.getFullYear() - 1);
    params.startTime = startDate.toISOString().split('T')[0];
    params.endTime = endDate.toISOString().split('T')[0];
  }

  await fetchList(params);
};

const fetchList = async (params) => {
  try {
    // 模拟API调用，实际项目中应该调用真实的API
    const mockData = generateMockData(params);
    
    paging.value.complete(mockData.records || []);
  } catch (error) {
    paging.value.complete(false);
  }
};

// 生成模拟数据
const generateMockData = (params) => {
  const workOrderTypes = ['运维工单', '巡检工单', '退款工单', '异常工单', '故障工单', '异常泊位'];
  const exceptionTypes = ['设备离线', '低电量预警', '秒图异常', '设备时间异常', '设备损坏', '网络异常', '其他异常'];
  const statuses = ['unassigned', 'pending', 'processing', 'completed'];
  const inspectors = ['张三', '李四', '王五', '赵六', '钱七', '孙八'];
  const parkingLots = ['停车场A区', '停车场B区', '停车场C区', '停车场D区'];
  
  let records = [];
  for (let i = 1; i <= 20; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const workOrderType = workOrderTypes[Math.floor(Math.random() * workOrderTypes.length)];
    const berthNumber = `A${(i + 100).toString()}`;
    const deviceSN = `SN${Date.now()}${i.toString().padStart(4, '0')}`;
    const parkingLot = parkingLots[Math.floor(Math.random() * parkingLots.length)];
    
    records.push({
      orderNo: `AT${Date.now()}${i.toString().padStart(3, '0')}`,
      berthNumber: berthNumber,
      deviceSN: deviceSN,
      workOrderType: workOrderType,
      exceptionType: exceptionTypes[Math.floor(Math.random() * exceptionTypes.length)],
      status: status,
      assigneeName: status === 'unassigned' ? null : inspectors[Math.floor(Math.random() * inspectors.length)],
      createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toLocaleString(),
      processTime: status === 'completed' ? new Date(Date.now() - Math.random() * 3 * 24 * 60 * 60 * 1000).toLocaleString() : null,
      parkingLot: parkingLot,
      remark: '这是一个测试备注信息',
      images: Math.random() > 0.5 ? ['/static/images/test1.jpg', '/static/images/test2.jpg'] : []
    });
  }
  
  // 根据关键词进行模糊搜索过滤
  if (params.keyword && params.keyword.trim()) {
    const keyword = params.keyword.trim().toLowerCase();
    records = records.filter(record => 
      record.berthNumber.toLowerCase().includes(keyword) ||
      record.deviceSN.toLowerCase().includes(keyword) ||
      record.parkingLot.toLowerCase().includes(keyword)
    );
  }
  
  // 根据状态筛选
  if (params.status > 0) {
    const statusMap = ['', 'unassigned', 'pending', 'completed'];
    const targetStatus = statusMap[params.status];
    if (targetStatus) {
      records = records.filter(record => record.status === targetStatus);
    }
  }
  
  // 分页处理
  const startIndex = (params.pageNum - 1) * params.pageSize;
  const endIndex = startIndex + params.pageSize;
  const paginatedRecords = records.slice(startIndex, endIndex);
  
  return { records: paginatedRecords };
};

// 页面挂载时获取数据
onMounted(() => {
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style scoped lang="scss">
.assign-task-list {
  padding: 20px;
}

.filter-section {
  .filter-item {
    margin-bottom: 20rpx;
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
  }
  
  .custom-time-section {
    margin-top: 20rpx;
    
    .time-picker-row {
      display: flex;
      align-items: center;
      
      .time-picker {
        flex: 1;
        
        .title {
          font-size: 28rpx;
          color: #333;
          margin-right: 20rpx;
        }
      }
    }
  }
}

.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 30rpx 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      
      .number {
        color: #007AFF;
      }
    }
    
    .status-badge {
      padding: 8rpx 20rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      font-weight: 500;
      
      &.status-unassigned {
        background: rgba(255, 152, 0, 0.1);
        color: #FF9800;
      }
      
      &.status-pending {
        background: rgba(255, 193, 7, 0.1);
        color: #FFC107;
      }
      
      &.status-processing {
        background: rgba(33, 150, 243, 0.1);
        color: #2196F3;
      }
      
      &.status-completed {
        background: rgba(76, 175, 80, 0.1);
        color: #4CAF50;
      }
    }
  }
  
  .card-content-box {
    padding: 30rpx;
    
    .content {
      .item {
        display: flex;
        margin-bottom: 16rpx;
        font-size: 28rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          color: #666;
          margin-right: 10rpx;
          min-width: 140rpx;
        }
        
        .value {
          color: #333;
          flex: 1;
          
          &.work-order-type {
            font-weight: 500;
            
            &.type-maintenance {
              color: #FF5722;
            }
            
            &.type-inspection {
              color: #9C27B0;
            }
            
            &.type-refund {
              color: #4CAF50;
            }
            
            &.type-exception {
              color: #FF9800;
            }
            
            &.type-fault {
              color: #F44336;
            }
            
            &.type-abnormal-berth {
              color: #607D8B;
            }
          }
          
          &.exception-type {
            font-weight: 500;
            
            &.type-offline {
              color: #F44336;
            }
            
            &.type-low-battery {
              color: #FF9800;
            }
            
            &.type-image-error {
              color: #9C27B0;
            }
            
            &.type-time-error {
              color: #2196F3;
            }
            
            &.type-damage {
              color: #F44336;
            }
            
            &.type-network-error {
              color: #FF5722;
            }
            
            &.type-other {
              color: #607D8B;
            }
          }
        }
      }
    }
    
    .card-footer {
      margin-top: 30rpx;
      
      .operate {
        display: flex;
        gap: 20rpx;
        
        .custom-style {
          flex: 1;
          height: 70rpx;
          font-size: 26rpx;
        }
      }
    }
  }
}

// 弹窗样式
.assign-modal,
.detail-modal,
.create-modal {
  width: 90vw;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-content {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
    
    .form-item {
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
        display: block;
      }
      
      .status-filter {
        margin: 20rpx 0;
        
        :deep(.up-radio-group) {
          display: flex;
          gap: 30rpx;
        }
      }
      
      .inspector-list {
        max-height: 300rpx;
        overflow-y: auto;
        border: 1rpx solid #e5e5e5;
        border-radius: 10rpx;
        
        .inspector-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20rpx;
          border-bottom: 1rpx solid #f5f5f5;
          cursor: pointer;
          
          &:last-child {
            border-bottom: none;
          }
          
          &.active {
            background: rgba(0, 122, 255, 0.1);
          }
          
          .inspector-info {
            flex: 1;
            
            .inspector-name {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 8rpx;
              display: block;
            }
            
            .inspector-phone {
              font-size: 24rpx;
              color: #999;
              margin-bottom: 8rpx;
              display: block;
            }
            
            .inspector-status {
              display: inline-block;
              padding: 4rpx 12rpx;
              border-radius: 12rpx;
              font-size: 20rpx;
              
              &.online {
                background: rgba(76, 175, 80, 0.1);
                color: #4CAF50;
              }
              
              &.offline {
                background: rgba(158, 158, 158, 0.1);
                color: #9E9E9E;
              }
            }
          }
          
          .selection-indicator {
            margin-left: 20rpx;
          }
        }
      }
      
      .image-upload {
        .image-list {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;
          
          .image-item {
            position: relative;
            width: 150rpx;
            height: 150rpx;
            
            .uploaded-image {
              width: 100%;
              height: 100%;
              border-radius: 10rpx;
              object-fit: cover;
            }
            
            .delete-btn {
              position: absolute;
              top: -10rpx;
              right: -10rpx;
              width: 40rpx;
              height: 40rpx;
              background: #ff4757;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
          
          .upload-btn {
            width: 150rpx;
            height: 150rpx;
            border: 2rpx dashed #ddd;
            border-radius: 10rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #fafafa;
            
            text {
              font-size: 24rpx;
              color: #999;
              margin-top: 10rpx;
            }
          }
        }
      }
    }
    
    .detail-item {
      display: flex;
      margin-bottom: 20rpx;
      font-size: 28rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .detail-label {
        color: #666;
        margin-right: 10rpx;
        min-width: 140rpx;
      }
      
      .detail-value {
        color: #333;
        flex: 1;
      }
      
      .detail-images {
        display: flex;
        flex-wrap: wrap;
        gap: 10rpx;
        
        .detail-image {
          width: 100rpx;
          height: 100rpx;
          border-radius: 8rpx;
          object-fit: cover;
        }
      }
    }
  }
  
  .modal-footer {
    padding: 30rpx;
    border-top: 1rpx solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
}
</style>